/**
 * 初始化聊天模块测试数据
 * 创建测试用户、就诊记录等
 */

const mongoose = require('../db/index');
const { LhxUser, LhxVisit, LhxMessage } = require('../db/lhx_models');

// 测试数据
const testUsers = [
  // 医生
  {
    userId: 'd001',
    name: '张医生',
    userType: 'doctor',
    department: '内科',
    avatar: '/avatars/doctor1.jpg',
    phone: '13800001001',
    status: 'active'
  },
  {
    userId: 'd002',
    name: '李医生',
    userType: 'doctor',
    department: '外科',
    avatar: '/avatars/doctor2.jpg',
    phone: '13800001002',
    status: 'active'
  },
  {
    userId: 'd003',
    name: '王医生',
    userType: 'doctor',
    department: '妇科',
    avatar: '/avatars/doctor3.jpg',
    phone: '13800001003',
    status: 'active'
  },
  
  // 患者（只有2个患者）
  {
    userId: 'p001',
    name: '患者张三',
    userType: 'patient',
    avatar: '/avatars/patient1.jpg',
    phone: '13900001001',
    status: 'active'
  },
  {
    userId: 'p002',
    name: '患者李四',
    userType: 'patient',
    avatar: '/avatars/patient2.jpg',
    phone: '13900001002',
    status: 'active'
  }
];

const testVisits = [
  // 患者p001的就诊记录（挂过前2个医生的号）
  {
    visitId: 'v001',
    patientId: 'p001',
    doctorId: 'd001',
    visitDate: new Date('2024-11-15'),
    department: '内科',
    diagnosis: '感冒发烧',
    visitType: 'first_visit',
    status: 'completed'
  },
  {
    visitId: 'v002',
    patientId: 'p001',
    doctorId: 'd002',
    visitDate: new Date('2024-11-20'),
    department: '外科',
    diagnosis: '外伤处理',
    visitType: 'first_visit',
    status: 'completed'
  },
  
  // 患者p002的就诊记录（也挂过前2个医生的号）
  {
    visitId: 'v003',
    patientId: 'p002',
    doctorId: 'd001',
    visitDate: new Date('2024-11-25'),
    department: '内科',
    diagnosis: '高血压咨询',
    visitType: 'first_visit',
    status: 'completed'
  },
  {
    visitId: 'v004',
    patientId: 'p002',
    doctorId: 'd002',
    visitDate: new Date('2024-11-28'),
    department: '外科',
    diagnosis: '体检咨询',
    visitType: 'first_visit',
    status: 'completed'
  }
  
  // 注意：患者没有挂过d003(王医生-妇科)的号，所以d003不会出现在患者的聊天列表中
];

const testMessages = [
  // p001和d001的聊天记录
  {
    roomId: 'p001_d001',
    senderId: 'p001',
    senderType: 'patient',
    content: '张医生您好，我想咨询一下感冒的后续治疗',
    messageType: 'text',
    timestamp: new Date('2024-12-01T09:00:00Z'),
    status: 'read'
  },
  {
    roomId: 'p001_d001',
    senderId: 'd001',
    senderType: 'doctor',
    content: '您好，请问现在还有什么症状吗？',
    messageType: 'text',
    timestamp: new Date('2024-12-01T09:05:00Z'),
    status: 'read'
  },
  {
    roomId: 'p001_d001',
    senderId: 'p001',
    senderType: 'patient',
    content: '咳嗽已经好很多了，但是还有点鼻塞',
    messageType: 'text',
    timestamp: new Date('2024-12-01T09:10:00Z'),
    status: 'read'
  },
  {
    roomId: 'p001_d001',
    senderId: 'd001',
    senderType: 'doctor',
    content: '那很好，鼻塞可以继续用药，多喝水多休息',
    messageType: 'text',
    timestamp: new Date('2024-12-01T09:15:00Z'),
    status: 'sent'
  },
  
  // p002和d002的聊天记录
  {
    roomId: 'p002_d002',
    senderId: 'p002',
    senderType: 'patient',
    content: '李医生您好，想咨询一下体检结果',
    messageType: 'text',
    timestamp: new Date('2024-12-01T14:00:00Z'),
    status: 'read'
  },
  {
    roomId: 'p002_d002',
    senderId: 'd002',
    senderType: 'doctor',
    content: '您好，体检报告我看了，整体情况良好',
    messageType: 'text',
    timestamp: new Date('2024-12-01T14:05:00Z'),
    status: 'sent'
  }
];

/**
 * 初始化数据
 */
async function initLhxData() {
  try {
    console.log('开始初始化聊天模块测试数据...');
    
    // 清空现有数据
    await Promise.all([
      LhxUser.deleteMany({}),
      LhxVisit.deleteMany({}),
      LhxMessage.deleteMany({})
    ]);
    console.log('清空现有数据完成');
    
    // 插入测试用户
    await LhxUser.insertMany(testUsers);
    console.log(`插入${testUsers.length}个测试用户`);
    
    // 插入测试就诊记录
    await LhxVisit.insertMany(testVisits);
    console.log(`插入${testVisits.length}个测试就诊记录`);
    
    // 插入测试消息
    await LhxMessage.insertMany(testMessages);
    console.log(`插入${testMessages.length}条测试消息`);
    
    console.log('聊天模块测试数据初始化完成！');
    
    // 显示数据统计
    const userCount = await LhxUser.countDocuments();
    const visitCount = await LhxVisit.countDocuments();
    const messageCount = await LhxMessage.countDocuments();
    
    console.log('数据统计:');
    console.log(`- 用户数量: ${userCount} (医生: ${testUsers.filter(u => u.userType === 'doctor').length}, 患者: ${testUsers.filter(u => u.userType === 'patient').length})`);
    console.log(`- 就诊记录: ${visitCount}`);
    console.log(`- 聊天消息: ${messageCount}`);
    
    // 显示测试场景
    console.log('\n可用测试场景:');
    console.log('1. 患者p001 可以与医生d001(张医生-内科), d002(李医生-外科)聊天');
    console.log('2. 患者p002 可以与医生d001(张医生-内科), d002(李医生-外科)聊天');
    console.log('3. 医生d003(王医生-妇科) 没有患者，不会出现在任何患者的聊天列表中');
    console.log('4. 已存在聊天记录：p001<->d001, p002<->d002');
    
    console.log('\n测试API示例:');
    console.log('GET /lhx/patient/p001/doctors - 获取p001可聊天医生');
    console.log('GET /lhx/doctor/d001/patients - 获取d001的聊天患者');
    console.log('GET /lhx/messages/p001_d001 - 获取聊天记录');
    
  } catch (error) {
    console.error('初始化数据失败:', error);
    throw error;
  }
}

/**
 * 清空数据
 */
async function clearLhxData() {
  try {
    await Promise.all([
      LhxUser.deleteMany({}),
      LhxVisit.deleteMany({}),
      LhxMessage.deleteMany({})
    ]);
    console.log('聊天模块数据清空完成');
  } catch (error) {
    console.error('清空数据失败:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const command = process.argv[2];
  
  if (command === 'clear') {
    clearLhxData()
      .then(() => process.exit(0))
      .catch(() => process.exit(1));
  } else {
    initLhxData()
      .then(() => process.exit(0))
      .catch(() => process.exit(1));
  }
}

module.exports = {
  initLhxData,
  clearLhxData,
  testUsers,
  testVisits,
  testMessages
};